﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GRWL.BZSC.UI.BaseDataSvc;
using System.Collections;
using GRWL.BZSC.UI.CustomCtrl;
using DgvFilterPopup;
using System.Reflection;

namespace GRWL.BZSC.UI
{
    public partial class MaterialFrm : BaseFrm
    {
        /// <summary>
        /// 当前选择项
        /// </summary>
        public SelectItem SelectorItem { get; set; }

        /// <summary>
        /// 记住当前设置的编码规则
        /// </summary>
        //public CodeRuleFrm.CodeRule codeRule { get; set; }

        public GRWL.BZSC.Common.EnumCommon.OptionType CurrentType { get; set; }

        /// <summary>
        /// 过滤器
        /// </summary>
        DgvFilterManager _DgvFm = null;

        public MaterialFrm()
        {
            InitializeComponent();
            this.BaseDataProxy = new GRWL.BZSC.UI.BaseDataSvc.BaseDataClient();
            GRWL.BZSC.Common.EventCommon.OptionUdTVEvnt += new GRWL.BZSC.Common.EventCommon.UpdateTreeViewDlgt(updateTreeView);
            GRWL.BZSC.Common.EventCommon.MaterialUdDGVEvnt += new GRWL.BZSC.Common.EventCommon.UpdateDataGridViewDlgt(updateDgv);
        }

        #region 处理外部委托
        /// <summary>
        /// 接收处理UpdateTreeViewDlgt
        /// </summary>
        /// <param name="o"></param>
        /// <param name="add"></param>
        private void updateTreeView(object o, EventArgs arg)
        {
            CommonEventArg<TB_Options> argObj = (CommonEventArg<TB_Options>)arg;
            if (this.uTreeView1.SelectedNode != null)
            {
                TreeNode node = new TreeNode();
                node.Name = argObj.t.id.ToString();
                node.Text = argObj.t.code + "[" + argObj.t.name + "]";
                node.Tag = argObj.t.code;

                if (argObj.OpType == Common.OperateType.Add)
                {
                    if (this.CurrentType == GRWL.BZSC.Common.EnumCommon.OptionType.物料分类)
                        this.uTreeView1.SelectedNode.Nodes.Add(node);
                    else
                        this.uTreeView2.SelectedNode.Nodes.Add(node);
                }
                else if (argObj.OpType == Common.OperateType.Update)
                {
                    if (this.CurrentType == GRWL.BZSC.Common.EnumCommon.OptionType.物料分类)
                        this.uTreeView1.SelectedNode.Text = node.Text;
                    else
                        this.uTreeView2.SelectedNode.Text = node.Text;
                }
            }
        }

        private void updateDgv(object o, EventArgs arg)
        {
            if (arg != null)
            {
                CommonEventArg<XMaterial> argObj = (CommonEventArg<XMaterial>)arg;
                string usable = argObj.t.Material.unusable ? "是" : "否";
                object[] ary =  { argObj.t.Material.code,argObj.t.Material.id,argObj.t.StockId, argObj.t.Material.cnName, argObj.t.Material.specs,argObj.t.CategoryName,
                                    argObj.t.StockDepotName,argObj.t.CurrentStockNum,argObj.t.BatchNo,argObj.t.Material.expire, argObj.t.DepartmentName,
                                    argObj.t.Material.brand, usable, argObj.t.Material.unit,argObj.t.TraderName, argObj.t.Material.source};
                DataTable dt = this.uDataGridView1.DataSource as DataTable;

                if (argObj.OpType == Common.OperateType.Add)
                {
                    DataRow dr = dt.NewRow();
                    OTConverter.ObjectPropertyToDataRow<XMaterial>(argObj.t, dt.Columns, dr);
                    OTConverter.ObjectPropertyToDataRow<TB_Material>(argObj.t.Material, dt.Columns, dr);
                    dt.Rows.Add(dr);
                    this.uDataGridView1.DataSource = dt;
                    //int rowId = this.uDataGridView1.Rows.Add(ary);
                    //this.uDataGridView1.Rows[rowId].Selected = true;
                }
                else if (argObj.OpType == Common.OperateType.Update)
                {
                    //ary[2] = Common.GetNullableValue<Int32>(this.uDataGridView1.SelectedRows[0].Cells[2].Value);//StockId
                    //ary[5] = this.uDataGridView1.SelectedRows[0].Cells[5].Value;//仓库
                    //ary[6] = this.uDataGridView1.SelectedRows[0].Cells[6].Value;//库存
                    //ary[7] = this.uDataGridView1.SelectedRows[0].Cells[7].Value;//批次
                    DataRow[] drs = dt.Select("Id=" + argObj.t.Material.id);
                    if (drs != null)
                    {
                        foreach (DataRow dr in drs)
                        {
                            OTConverter.ObjectPropertyToDataRow<XMaterial>(argObj.t, dt.Columns, dr);
                            OTConverter.ObjectPropertyToDataRow<TB_Material>(argObj.t.Material, dt.Columns, dr);
                        }
                    }
                    dt.AcceptChanges();
                    this.uDataGridView1.DataSource = dt;
                    //this.uDataGridView1.SelectedRows[0].SetValues(ary);
                }
                else if (argObj.OpType == Common.OperateType.Delete)
                { this.uDataGridView1.Rows.Remove(this.uDataGridView1.SelectedRows[0]); }
            }
        }
        #endregion

        private void MaterialFrm_Load(object sender, EventArgs e)
        {
            this.BaseDataProxy.Open();

            this._DgvFm = new DgvFilterManager();
            this._DgvFm.ColumnFilterAdding += new ColumnFilterEventHandler(initDgvFilter);
            initDgvColumns();

            this.CurrentType = GRWL.BZSC.Common.EnumCommon.OptionType.物料分类;
            bindTree(this.uTreeView1);

            //默认的编码规则
            getCurrentCodeRule(true);
        }

        /// <summary>
        /// 初始化表格列
        /// </summary>
        private void initDgvColumns()
        {
            this.uDataGridView1.AutoGenerateColumns = false;
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "Code", "代号", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "Id", "物料Id", false, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "StockId", "库存Id", false, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "CnName", "名称", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "Specs", "规格", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "CategoryName", "分类", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "StockDepotName", "仓库", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "CurrentStockNum", "库存", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "BatchNo", "批号", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "expire", "有效期", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "DepartmentCode", "生产部门代号", false, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "DepartmentName", "生产部门", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "Brand", "品牌", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewCheckBoxColumn(), "Unusable", "停用", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "Unit", "单位", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "DepotArea", "库位", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "PrjtCode", "工程号", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "PrjtId", "工程Id", false, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "ProviderName", "主供应商", true, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "ProviderCode", "主供应商号", false, true, null);
            Common.AddDgvColumn(this.uDataGridView1, new DataGridViewTextBoxColumn(), "Source", "来源", true, true, null);
        }

        /// <summary>
        /// Dgv字段绑定过滤器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void initDgvFilter(object sender, ColumnFilterEventArgs e)
        {
            switch (e.Column.DataPropertyName)
            {
                case "CategoryName":
                    {
                        e.ColumnFilter = new DgvComboBoxColumnFilter();
                        break;
                    }
                case "CurrentStockNum":
                    {
                        e.ColumnFilter = new DgvNumRangeColumnFilter();
                        break;
                    }
                case "BatchNo":
                    {
                        e.ColumnFilter = new DgvComboBoxColumnFilter();
                        break;
                    }
                case "StockDepotName":
                    {
                        e.ColumnFilter = new DgvComboBoxColumnFilter();
                        break;
                    }
                case "DepartmentName":
                    {
                        e.ColumnFilter = new DgvComboBoxColumnFilter();
                        break;
                    }
                case "Brand":
                    {
                        e.ColumnFilter = new DgvComboBoxColumnFilter();
                        break;
                    }
                case "Unusable":
                    {
                        e.ColumnFilter = new DgvComboBoxColumnFilter();
                        break;
                    }
                case "expire":
                    {
                        e.ColumnFilter = new DgvDateColumnFilter();
                        break;
                    }
                case "Unit":
                    {
                        e.ColumnFilter = new DgvComboBoxColumnFilter();
                        break;
                    }
                case "Source":
                    {
                        e.ColumnFilter = new DgvComboBoxColumnFilter();
                        break;
                    }
                case "ProviderName":
                    {
                        e.ColumnFilter = new DgvComboBoxColumnFilter();
                        break;
                    }
                default:
                    {
                        e.ColumnFilter = new DgvTextBoxColumnFilter();
                        break;
                    }
            }
            e.Handled = true;
        }

        private void bindTree(UserCtrl.UTreeView tv)
        {
            TB_Options[] options = this.BaseDataProxy.GetOptionTree(this.CurrentType.ToString());
            Common.BindOptionTree(tv, options, this.CurrentType.ToString());
            if (this.CurrentType == GRWL.BZSC.Common.EnumCommon.OptionType.仓库分类)
            {
                TB_Depot[] ary = this.BaseDataProxy.FindDepots(string.Empty, string.Empty, null);
                if (ary != null)
                    loadDepot(ary);
            }
        }

        private void loadDepot(TB_Depot[] ary)
        {
            foreach (TreeNode node in this.uTreeView2.Nodes[0].Nodes)
            {
                if (node.ImageIndex == 2)
                {
                    int category = Convert.ToInt32(node.Name);
                    var query = from q in ary where q.type == category select q;
                    if (query != null)
                    {
                        foreach (TB_Depot d in query)
                        {
                            TreeNode child = new TreeNode();
                            child.Name = d.id.ToString();
                            child.Tag = d.code;
                            child.Text = "[" + d.code + "]" + d.name;
                            child.ImageIndex = 3;
                            node.Nodes.Add(child);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 数据绑定到dgv
        /// </summary>
        /// <param name="type"></param>
        /// <param name="depotCategory"></param>
        /// <param name="depot"></param>
        private void bindGV(int? type, int? depotCategory, int? depot)
        {
            if (this._DgvFm.DataGridView != null)
                this._DgvFm.ActivateAllFilters(false);
            QMaterial[] objAry = this.BaseDataProxy.FindMaterials(true, type, depotCategory, depot, this.textBox1.Text.Trim(), this.textBox2.Text.Trim(), this.textBox3.Text.Trim(),null,null,null);
            if (objAry != null)
            {
                DataTable dt = objAry.ToDataTable();
                this.uDataGridView1.DataSource = dt;
                if (dt.Rows.Count > 0)
                    this._DgvFm.DataGridView = this.uDataGridView1;
            }
        }

        private void uTreeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Name != string.Empty)
            {
                bindGV(Convert.ToInt32(e.Node.Name), null, null);
            }
            else
                bindGV(null, null, null);
        }

        private void uTreeView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Point ClickPoint = new Point(e.X, e.Y);
                TreeNode CurrentNode = this.uTreeView1.GetNodeAt(ClickPoint);
                if (CurrentNode != null)
                {
                    this.uTreeView1.SelectedNode = CurrentNode;
                    CurrentNode.ContextMenuStrip = this.contextMenuStrip1;
                }
            }
        }

        private void uTabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.uTabControl1.SelectedIndex == 1)
            {
                this.CurrentType = GRWL.BZSC.Common.EnumCommon.OptionType.仓库分类;
                bindTree(this.uTreeView2);
            }
            else
            {
                this.CurrentType = GRWL.BZSC.Common.EnumCommon.OptionType.物料分类;
                bindTree(this.uTreeView1);
            }
        }

        private void 新增ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            addOption();
        }

        private void addOption()
        {
            Control ctrl = this.contextMenuStrip1.SourceControl;
            if (ctrl != null)
            {
                UserCtrl.UTreeView tv = (UserCtrl.UTreeView)ctrl;
                EditOptionFrm frm = new EditOptionFrm();
                frm.EditMode = false;
                int parentId = tv.SelectedNode.Name == string.Empty ? 0 : Convert.ToInt32(tv.SelectedNode.Name);
                frm.ParentId = parentId;
                frm.OType = this.CurrentType;
                frm.codeRule = this.codeRule;
                frm.ShowDialog(this);
            }
        }

        private void 修改ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            editOption();
        }

        private void editOption()
        {
            Control ctrl = this.contextMenuStrip1.SourceControl;
            if (ctrl != null)
            {
                UserCtrl.UTreeView tv = (UserCtrl.UTreeView)ctrl;
                if (!string.IsNullOrEmpty(tv.SelectedNode.Name))
                {
                    EditOptionFrm frm = new EditOptionFrm();
                    frm.EditMode = true;
                    frm.Id = Convert.ToInt32(tv.SelectedNode.Name);
                    frm.ShowDialog(this);
                }
            }
        }

        private void 删除1ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            delOption();
        }

        private void delOption()
        {
            Control ctrl = this.contextMenuStrip1.SourceControl;
            if (ctrl != null)
            {
                UserCtrl.UTreeView tv = (UserCtrl.UTreeView)ctrl;
                if (!string.IsNullOrEmpty(tv.SelectedNode.Name))
                {
                    if (MessageBox.Show("确认删除该项吗？", "删除提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        if (this.BaseDataProxy.DeleteOption(Convert.ToInt32(tv.SelectedNode.Name)))
                            tv.Nodes.Remove(tv.SelectedNode);
                    }
                }
            }
        }

        private void 编码规则ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Control ctrl = this.contextMenuStrip1.SourceControl;
            if (ctrl != null)
            {
                UserCtrl.UTreeView tv = (UserCtrl.UTreeView)ctrl;
                if (!string.IsNullOrEmpty(tv.SelectedNode.Name))
                {
                    CodeRuleFrm frm = new CodeRuleFrm(this.CurrentType.ToString() + "编码规则");
                    frm.Rule = this.codeRule;
                    frm.inHeader = tv.SelectedNode.Tag.ToString();
                    if (frm.ShowDialog() == DialogResult.OK)
                    {
                        this.codeRule = frm.Rule;
                    }
                }
            }
        }

        private void uTreeView2_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Name != string.Empty)
            {
                if (e.Node.ImageIndex == 3)
                    bindGV(null, null, Convert.ToInt32(e.Node.Name));
                else if (e.Node.ImageIndex == 2)
                    bindGV(null, Convert.ToInt32(e.Node.Name), null);
                else
                    bindGV(null, null, null);
            }
            else
                bindGV(null, null, null);
        }

        private void uTreeView2_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Point ClickPoint = new Point(e.X, e.Y);
                TreeNode CurrentNode = this.uTreeView2.GetNodeAt(ClickPoint);
                if (CurrentNode != null)
                {
                    this.uTreeView2.SelectedNode = CurrentNode;
                    CurrentNode.ContextMenuStrip = this.contextMenuStrip1;
                }
            }
        }

        private void uDataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1 && this.uDataGridView1.SelectedRows.Count > 0)
            {
                EditMaterialFrm frm = new EditMaterialFrm();
                frm.Id = Convert.ToInt32(this.uDataGridView1.SelectedRows[0].Cells[1].Value.ToString());
                if (this.uDataGridView1.SelectedRows[0].Cells[2].Value != null && this.uDataGridView1.SelectedRows[0].Cells[2].Value != DBNull.Value)
                    frm.StockId = Convert.ToInt32(this.uDataGridView1.SelectedRows[0].Cells[2].Value.ToString());
                frm.EditMode = true;
                frm.codeRule = getCurrentCodeRule(false);
                frm.ShowDialog(this);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            EditMaterialFrm frm = new EditMaterialFrm();
            frm.EditMode = false;
            if (this.uTreeView1.SelectedNode != null && !string.IsNullOrEmpty(this.uTreeView1.SelectedNode.Name))
            {
                SelectItem item = new SelectItem();
                item.Key = this.uTreeView1.SelectedNode.Tag.ToString();
                item.Name = this.uTreeView1.SelectedNode.Text;
                item.Value = this.uTreeView1.SelectedNode.Name;
                frm.CurrentCategory = item;
            }
            frm.codeRule = getCurrentCodeRule(false);
            frm.ShowDialog(this);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (this.uDataGridView1.SelectedRows.Count > 0)
            {
                if (MessageBox.Show("确认删除该项吗？", "删除提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    //bool delOk = this.BaseDataProxy.DeleteMaterial(Convert.ToInt32(this.uDataGridView1.SelectedRows[0].Cells[1].Value.ToString()));
                    SPResult spr = this.BaseDataProxy.SPDeleteMaterial(Convert.ToInt32(this.uDataGridView1.SelectedRows[0].Cells[1].Value.ToString()));
                    if (spr.Ok)
                        this.uDataGridView1.Rows.Remove(this.uDataGridView1.SelectedRows[0]);
                    else
                        MessageBox.Show("删除失败，" + spr.Msg);
                }
            }
        }

        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            base.OnFormClosed(e);
            GRWL.BZSC.Common.EventCommon.OptionUdTVEvnt -= new GRWL.BZSC.Common.EventCommon.UpdateTreeViewDlgt(updateTreeView);
            GRWL.BZSC.Common.EventCommon.MaterialUdDGVEvnt -= new GRWL.BZSC.Common.EventCommon.UpdateDataGridViewDlgt(updateDgv);
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            bindGV(null, null, null);
        }

        private void btnCodeRule_Click(object sender, EventArgs e)
        {
            CodeRuleFrm frm = new CodeRuleFrm("物料编码规则");
            frm.Rule = getCurrentCodeRule(false);
            if (frm.ShowDialog() == DialogResult.OK)
                this.codeRule = frm.Rule;
        }

        /// <summary>
        /// 获取当前编码规则
        /// </summary>
        /// <param name="init"></param>
        /// <returns></returns>
        private CodeRuleFrm.CodeRule getCurrentCodeRule(bool init)
        {
            if (init)
            {
                if (this.codeRule == null)
                    this.codeRule = new CodeRuleFrm.CodeRule();
                this.codeRule.addParent = true;
                this.codeRule.autoCode = false;
                this.codeRule.autoFill = true;
                this.codeRule.len = 4;
            }

            if (this.uTreeView1.SelectedNode != null && this.uTreeView1.SelectedNode.Tag != null && this.codeRule.addParent)
                this.codeRule.header = this.uTreeView1.SelectedNode.Tag.ToString();//前加分类编码   
            else
                this.codeRule.header = string.Empty;
            return this.codeRule;
        }

        private void uDataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(this.uDataGridView1);
        }

        private void uDataGridView1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(this.uDataGridView1);
        }

    }
}

